import { ValidateErrorInfo } from '@/ts/base/model';
/**
 * 将代码包裹在无参函数里面并导出
 * @param code 代码字符串
 * @param fnName 函数名
 * @param async 是否为异步函数
 */
export function wrapExportedFunction(code: string, fnName: string, async = false): string {
  // 移除可能的 export/import 语句
  code = code.replace(/^(import|export).+?\n/gm, '');
  
  // 构建函数字符串
  const functionStr = `
${async ? 'async ' : ''}function ${fnName}() {
  ${code}
}
export default ${fnName};
`;

  return functionStr.trim();
}
export function mapErrorToValidateInfo(error: any, position?: string): ValidateErrorInfo {
  let msg = String(error);
  if (error instanceof Error) {
    msg = error.message;
    let match: RegExpExecArray | null;
    if ((match = /^(.+) is not defined/.exec(msg))) {
      msg = `变量或函数 '${match[1]}' 没有定义`;
    } else if ((match = /Unexpected token.+/.exec(msg))) {
      msg = '语法错误：' + msg;
    } else if ((match = /Cannot read properties of undefined \(reading '(.+)'\)/.exec(msg))) {
      msg = `尝试对空值读取属性 '${match[1]}'`;
    }
  }

  return {
    errorCode: 'ERR_FAILED',
    errorLevel: 'error',
    message: `错误：${msg} \n请检查配置`,
    position,
  };
}